import React, { useState, useEffect } from 'react';
import { http, API_PATH } from '../utils/http';
import MarkdownRenderer from '../components/MarkdownRenderer';

// 文章主题状态
type ArticleStatus = 'pending' | 'completed' | 'processing' | 'failed';

// 状态常量 - 改为非导出常量
const ARTICLE_STATUS = {
    PENDING: 'pending',     // 待执行
    COMPLETED: 'completed', // 完成执行
    PROCESSING: 'processing', // 执行中
    FAILED: 'failed'        // 执行失败
} as const;

// 状态对应的文字描述
const statusTextMap: Record<ArticleStatus, string> = {
    pending: '待执行',
    completed: '完成执行',
    processing: '执行中',
    failed: '执行失败'
};

// 状态对应的颜色
const statusColorMap: Record<ArticleStatus, string> = {
    pending: 'bg-indigo-50 text-indigo-600 border border-indigo-200',
    completed: 'bg-emerald-50 text-emerald-600 border border-emerald-200',
    processing: 'bg-sky-50 text-sky-600 border border-sky-200',
    failed: 'bg-rose-50 text-rose-600 border border-rose-200'
};

// 文章主题接口
interface ArticleTopic {
    id: string;
    topic: string;
    status: ArticleStatus;
    created_at: number;
    is_used: boolean; // 是否已使用
}

const TopicSquare: React.FC = () => {
    // 文章主题列表
    const [topics, setTopics] = useState<ArticleTopic[]>([]);
    // 加载状态
    const [loading, setLoading] = useState(false);
    // 当前选中的状态筛选
    const [statusFilter, setStatusFilter] = useState<ArticleStatus | null>(null);
    // 分页信息
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
    });
    // 新建主题弹窗可见性
    const [modalVisible, setModalVisible] = useState(false);
    // 新建主题表单数据
    const [newTopic, setNewTopic] = useState('');
    // 一键生成确认弹窗可见性
    const [generateConfirmVisible, setGenerateConfirmVisible] = useState(false);

    // Toast提示组件
    const [toast, setToast] = useState<{ message: string; type: 'success' | 'error' | 'info'; visible: boolean }>({
        message: '',
        type: 'info',
        visible: false
    });

    // 显示Toast
    const showToast = (message: string, type: 'success' | 'error' | 'info' = 'info') => {
        setToast({ message, type, visible: true });
        // 自动关闭
        setTimeout(() => {
            setToast(prev => ({ ...prev, visible: false }));
        }, 2000);
    };

    // 获取主题列表
    const fetchTopics = async (page = pagination.current, pageSize = pagination.pageSize, status: ArticleStatus | null = statusFilter) => {
        setLoading(true);
        try {
            const params: Record<string, unknown> = {
                page,
                page_size: pageSize,
                include_used: true // 包含使用状态信息
            };

            if (status) {
                params.status = status;
            }

            const response = await http.get<ArticleTopic>(API_PATH.ARTICLE.LIST, params);

            response.onSuccess(() => {
                setTopics(response.list);
                const meta = response.meta;
                if (meta) {
                    setPagination({
                        current: meta.page,
                        pageSize: meta.page_size,
                        total: meta.total
                    });
                }
            }).onError((code, msg) => {
                console.error(`获取列表失败: 错误码 ${code}, 消息: ${msg}`);
                showToast(`获取主题列表失败: ${msg}`, 'error');
            });

        } catch (error) {
            console.error('网络请求异常:', error);
            showToast('网络请求异常', 'error');
        } finally {
            setLoading(false);
        }
    };

    // 一键生成全部主题文章
    const handleGenerateAll = async () => {
        try {
            setLoading(true);

            interface GenerationResponse {
                pending: number;
                processing: number;
                completed: number;
                failed: number;
                total: number;
                enqueued: number;
            }

            const response = await http.post<GenerationResponse>(API_PATH.ARTICLE.START_GENERATION);

            response.onSuccess((data) => {
                // 根据API返回的结构，data可能是单个对象或数组
                // 如果是单个对象（SingleResponse），可以直接访问其属性
                if (data && !Array.isArray(data)) {
                    showToast(`已将${data.enqueued}个任务加入队列`, 'success');
                }
                // 刷新列表以更新状态
                fetchTopics();
            }).onError((code, msg) => {
                console.error(`生成失败: 错误码 ${code}, 消息: ${msg}`);
                showToast(`一键生成失败: ${msg}`, 'error');
            });

        } catch (error) {
            console.error('网络请求异常:', error);
            showToast('网络请求异常', 'error');
        } finally {
            setLoading(false);
        }
    };

    // 创建主题
    const createTopic = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!newTopic.trim()) {
            showToast('请输入主题内容', 'info');
            return;
        }

        try {
            setLoading(true);
            const response = await http.post<ArticleTopic>(
                API_PATH.ARTICLE.CREATE,
                { topic: newTopic } as Record<string, unknown>
            );

            response.onSuccess(() => {
                // 隐藏弹窗
                setModalVisible(false);
                // 清空输入
                setNewTopic('');
                // 刷新列表
                fetchTopics();
                // 显示成功提示
                showToast('创建主题成功', 'success');
            }).onError((code, msg) => {
                console.error(`创建失败: 错误码 ${code}, 消息: ${msg}`);
                showToast(`创建失败: ${msg}`, 'error');
            });

        } catch (error) {
            console.error('网络请求异常:', error);
            showToast('网络请求异常', 'error');
        } finally {
            setLoading(false);
        }
    };

    // 首次加载获取数据
    useEffect(() => {
        fetchTopics();
    }, []);

    // 处理状态筛选变化
    const handleStatusChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
        const value = e.target.value;
        let newStatus: ArticleStatus | null = null;

        if (value && value !== 'all') {
            newStatus = value as ArticleStatus;
        }

        setStatusFilter(newStatus);
        fetchTopics(1, pagination.pageSize, newStatus);
    };

    // 格式化时间
    const formatDate = (timestamp: number) => {
        const date = new Date(timestamp);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false
        });
    };

    // 显示一键生成确认弹窗
    const showGenerateConfirm = () => {
        setGenerateConfirmVisible(true);
    };

    // 返回首页
    const handleBack = () => {
        window.location.href = '/';
    };

    // 导航到主题详情页
    const navigateToDetail = (topicId: string) => {
        window.location.href = `/topic-detail?id=${topicId}`;
    };

    return (
        <div className="min-h-screen bg-gradient-to-br from-gray-50 via-white to-gray-100 bg-fixed">
            {/* 背景装饰元素 */}
            <div className="fixed inset-0 overflow-hidden pointer-events-none">
                <div className="absolute top-40 right-[10%] w-64 h-64 bg-indigo-200/20 rounded-full mix-blend-multiply filter blur-2xl opacity-20 animate-floating" style={{ animationDelay: '0s' }}></div>
                <div className="absolute top-20 left-[5%] w-96 h-96 bg-purple-200/30 rounded-full mix-blend-multiply filter blur-2xl opacity-20 animate-floating" style={{ animationDelay: '-2s' }}></div>
                <div className="absolute top-1/2 left-[40%] w-44 h-44 bg-green-200/30 rounded-full mix-blend-multiply filter blur-2xl opacity-20 animate-floating" style={{ animationDelay: '-1s' }}></div>
                <div className="absolute bottom-40 right-[30%] w-72 h-72 bg-yellow-200/30 rounded-full mix-blend-multiply filter blur-2xl opacity-20 animate-floating" style={{ animationDelay: '-3s' }}></div>
            </div>

            {/* 顶部导航栏 */}
            <header className="bg-white border-b border-gray-200 shadow-sm sticky top-0 z-10">
                <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                    <div className="flex justify-between items-center h-16">
                        <div className="flex items-center">
                            <button
                                onClick={handleBack}
                                className="inline-flex items-center px-3.5 py-2 border border-gray-200/70 rounded-lg text-sm font-medium text-gray-700 bg-white/90 hover:bg-indigo-50/80 hover:text-indigo-600 hover:border-indigo-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-all duration-200 shadow-sm backdrop-blur-sm"
                            >
                                <svg className="w-5 h-5 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
                                </svg>
                                返回首页
                            </button>
                        </div>
                        <h1 className="text-xl font-semibold text-gray-900 relative">
                            <span className="relative z-10 bg-clip-text text-transparent bg-gradient-to-r from-indigo-600 to-purple-600">主题广场</span>
                            <span className="absolute inset-x-0 bottom-0 h-1 bg-gradient-to-r from-indigo-200 to-purple-200 -z-0 rounded-full transform translate-y-1"></span>
                        </h1>
                        <div className="w-28"></div> {/* 占位元素 */}
                    </div>
                </div>
            </header>

            {/* 主内容区 */}
            <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
                {/* 筛选和操作区 */}
                <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-4 mb-6 hover:shadow-md transition-all duration-300">
                    <div className="flex flex-wrap items-center justify-between gap-4">
                        <div className="flex items-center gap-4">
                            <label className="text-gray-700 font-medium">状态筛选:</label>
                            <div className="relative">
                                <select
                                    className="appearance-none bg-white border border-gray-200 rounded-lg pl-4 pr-10 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 text-sm text-gray-700 shadow-sm transition-all duration-200 hover:border-indigo-200"
                                    value={statusFilter || 'all'}
                                    onChange={handleStatusChange}
                                >
                                    <option value="all">全部</option>
                                    {Object.values(ARTICLE_STATUS).map((value) => (
                                        <option key={value} value={value}>
                                            {statusTextMap[value as ArticleStatus]}
                                        </option>
                                    ))}
                                </select>
                                <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-500">
                                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 9l-7 7-7-7" />
                                    </svg>
                                </div>
                            </div>
                        </div>
                        <div className="flex space-x-3">
                            <button
                                onClick={showGenerateConfirm}
                                className="inline-flex items-center px-4 py-2 border border-transparent rounded-lg shadow-sm text-sm font-medium text-white bg-gradient-to-r from-green-500 to-emerald-600 hover:from-green-600 hover:to-emerald-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 transition-all duration-200"
                            >
                                <svg className="-ml-1 mr-2 h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
                                </svg>
                                一键生成
                            </button>
                            <button
                                onClick={() => setModalVisible(true)}
                                className="inline-flex items-center px-4 py-2 border border-transparent rounded-lg shadow-sm text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-600 hover:from-indigo-600 hover:to-purple-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-all duration-200"
                            >
                                <svg className="-ml-1 mr-2 h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 4v16m8-8H4"></path>
                                </svg>
                                创建主题
                            </button>
                        </div>
                    </div>
                </div>

                {/* 主题列表区域 */}
                {loading && topics.length === 0 ? (
                    <div className="flex justify-center items-center py-16">
                        <div className="flex flex-col items-center bg-white p-8 rounded-xl shadow-sm border border-gray-100">
                            <svg className="animate-spin h-10 w-10 text-indigo-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                            </svg>
                            <span className="mt-3 text-gray-600 font-medium">加载中...</span>
                        </div>
                    </div>
                ) : topics.length === 0 ? (
                    <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-12 text-center">
                        <div className="flex flex-col items-center">
                            <svg className="w-16 h-16 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"></path>
                            </svg>
                            <h3 className="mt-4 text-lg font-medium text-gray-900">暂无主题</h3>
                            <p className="mt-1 text-gray-500">创建一个新主题开始使用吧</p>
                            <button
                                onClick={() => setModalVisible(true)}
                                className="mt-6 inline-flex items-center px-4 py-2 border border-transparent rounded-lg shadow-sm text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-indigo-600 hover:from-indigo-600 hover:to-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-all duration-200"
                            >
                                <svg className="-ml-1 mr-2 h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 4v16m8-8H4"></path>
                                </svg>
                                创建主题
                            </button>
                        </div>
                    </div>
                ) : (
                    <div className="grid grid-cols-1 sm:grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-3 2xl:grid-cols-4 gap-4 md:gap-6">
                        {topics.map((topic, index) => {
                            // 计算序号
                            const topicNumber = (pagination.current - 1) * pagination.pageSize + index + 1;

                            return (
                                <div
                                    key={topic.id}
                                    className="group relative bg-white rounded-xl shadow-sm border border-gray-100 hover:shadow-lg hover:shadow-indigo-100/50 hover:border-indigo-200 transition-all duration-300 overflow-hidden cursor-pointer flex flex-col h-auto min-h-[240px] transform hover:-translate-y-1 hover:scale-[1.02]"
                                    onClick={() => navigateToDetail(topic.id)}
                                >
                                    <div className="absolute inset-0 bg-gradient-to-r from-indigo-500/5 via-purple-500/5 to-indigo-500/5 opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>
                                    {/* 标题栏 - 带有状态和序号 */}
                                    <div className="relative">
                                        {/* 序号徽章 */}
                                        <div className="absolute top-3 left-3 z-10">
                                            <div className={`w-8 h-8 flex items-center justify-center rounded-lg text-white font-bold shadow-sm ${topic.status === 'completed' ? 'bg-gradient-to-br from-emerald-500 to-emerald-600 ring-2 ring-emerald-200/50' :
                                                topic.status === 'failed' ? 'bg-gradient-to-br from-rose-500 to-rose-600 ring-2 ring-rose-200/50' :
                                                    topic.status === 'processing' ? 'bg-gradient-to-br from-sky-500 to-sky-600 ring-2 ring-sky-200/50' :
                                                        'bg-gradient-to-br from-indigo-500 to-indigo-600 ring-2 ring-indigo-200/50'
                                                }`}>
                                                {topicNumber}
                                            </div>
                                        </div>

                                        {/* 状态标签 */}
                                        <div className="absolute top-3 right-3 z-10">
                                            <span className={`inline-flex items-center px-2.5 py-1 rounded-md text-xs font-medium shadow-sm ${statusColorMap[topic.status]}`}>
                                                {statusTextMap[topic.status]}
                                            </span>
                                        </div>

                                        {/* 标题背景 */}
                                        <div className="h-16 bg-gradient-to-r from-gray-50 via-white to-gray-50"></div>
                                    </div>

                                    {/* 内容区域 */}
                                    <div className="flex-grow p-4 relative">
                                        <div className="max-h-[180px] overflow-auto pr-2 markdown-content custom-scrollbar">
                                            <MarkdownRenderer
                                                content={topic.topic}
                                                isCompact={true}
                                            />
                                        </div>
                                        {/* 渐变遮罩，提示有更多内容 */}
                                        <div className="absolute bottom-0 left-0 right-0 h-14 bg-gradient-to-t from-white via-white to-transparent pointer-events-none flex items-end justify-center pb-1">
                                            <span className="bg-indigo-50 text-indigo-600 text-xs px-3 py-1 rounded-full border border-indigo-200 shadow-sm font-medium flex items-center transform transition-transform group-hover:scale-105 animate-gentle-pulse">
                                                <svg className="w-3 h-3 mr-1" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                                                </svg>
                                                查看完整内容
                                            </span>
                                        </div>
                                    </div>

                                    {/* 底部区域：日期和使用状态 */}
                                    <div className="flex justify-between items-center px-4 py-3 border-t border-gray-100 bg-gray-50">
                                        {/* 日期和使用状态 */}
                                        <div className="flex items-center gap-2">
                                            <span className="text-xs text-gray-500">
                                                {formatDate(topic.created_at).split(' ')[0]}
                                            </span>
                                            {topic.is_used !== undefined && (
                                                <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${topic.is_used
                                                    ? 'bg-green-50 text-green-600 border border-green-200'
                                                    : 'bg-yellow-50 text-yellow-600 border border-yellow-200'
                                                    }`}>
                                                    {topic.is_used ? '已使用' : '未使用'}
                                                </span>
                                            )}
                                        </div>

                                        {/* 查看详情 */}
                                        <div className="text-xs text-indigo-600 font-medium opacity-0 group-hover:opacity-100 transition-all duration-300 flex items-center transform group-hover:translate-x-1">
                                            <span>查看详情</span>
                                            <svg className="w-3.5 h-3.5 ml-1 group-hover:animate-pulse" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 5l7 7-7 7" />
                                            </svg>
                                        </div>
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                )}

                {/* 分页 */}
                {topics.length > 0 && (
                    <div className="mt-8 flex items-center justify-between">
                        <div className="flex items-center gap-2">
                            <button
                                onClick={() => fetchTopics(pagination.current - 1)}
                                disabled={pagination.current === 1}
                                className={`px-4 py-2 rounded-lg border text-sm font-medium flex items-center ${pagination.current === 1
                                    ? 'bg-gray-50 text-gray-400 border-gray-200 cursor-not-allowed'
                                    : 'bg-white text-gray-700 border-gray-300 hover:bg-gray-50 transition-colors duration-200'
                                    }`}
                            >
                                <svg className="w-5 h-5 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 19l-7-7 7-7" />
                                </svg>
                                上一页
                            </button>
                            <span className="px-4 py-2 bg-white border border-gray-300 rounded-lg text-sm text-gray-700">
                                第 {pagination.current} 页，共 {Math.ceil(pagination.total / pagination.pageSize)} 页
                            </span>
                            <button
                                onClick={() => fetchTopics(pagination.current + 1)}
                                disabled={pagination.current * pagination.pageSize >= pagination.total}
                                className={`px-4 py-2 rounded-lg border text-sm font-medium flex items-center ${pagination.current * pagination.pageSize >= pagination.total
                                    ? 'bg-gray-50 text-gray-400 border-gray-200 cursor-not-allowed'
                                    : 'bg-white text-gray-700 border-gray-300 hover:bg-gray-50 transition-colors duration-200'
                                    }`}
                            >
                                下一页
                                <svg className="w-5 h-5 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 5l7 7-7 7" />
                                </svg>
                            </button>
                        </div>
                        <div className="text-sm text-gray-600 font-medium">
                            共 {pagination.total} 条记录
                        </div>
                    </div>
                )}
            </main>

            {/* 新建主题弹窗 */}
            {modalVisible && (
                <div className="fixed inset-0 bg-black/70 flex items-center justify-center p-4 z-50 animate-fadein">
                    <div className="bg-white rounded-2xl w-full max-w-md shadow-2xl animate-scalein border border-gray-100">
                        <div className="relative">
                            {/* 头部区域 */}
                            <div className="px-6 py-5 border-b border-gray-100">
                                <h3 className="text-lg font-semibold text-gray-800 relative">
                                    <span className="relative z-10">新建主题</span>
                                    <span className="absolute inset-x-0 bottom-0 h-2 bg-indigo-100/50 -z-0 rounded-full transform -translate-y-2"></span>
                                </h3>
                                <button
                                    onClick={() => setModalVisible(false)}
                                    className="absolute top-5 right-6 text-gray-400 hover:text-gray-600 transition-colors duration-200 hover:rotate-90 transform"
                                >
                                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
                                    </svg>
                                </button>
                            </div>

                            {/* 表单内容 */}
                            <div className="px-6 py-5">
                                <form onSubmit={createTopic}>
                                    <div className="mb-5">
                                        <label className="block text-gray-700 text-sm font-medium mb-2">
                                            主题内容
                                        </label>
                                        <div className="relative group">
                                            <div className="absolute -inset-0.5 bg-gradient-to-r from-indigo-500 to-purple-500 rounded-xl opacity-25 group-focus-within:opacity-100 transition duration-300 blur"></div>
                                            <div className="relative">
                                                <textarea
                                                    className="w-full px-4 py-3 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent resize-none text-gray-700 shadow-sm transition-all duration-200 bg-white"
                                                    rows={6}
                                                    placeholder="请输入主题内容，支持Markdown格式..."
                                                    value={newTopic}
                                                    onChange={(e) => setNewTopic(e.target.value)}
                                                    maxLength={500}
                                                />
                                                <div className="absolute bottom-3 right-3 text-gray-400 text-xs bg-white px-2 rounded-full">
                                                    {newTopic.length}/500
                                                </div>
                                            </div>
                                        </div>
                                        <p className="mt-2 text-xs text-gray-500">支持Markdown格式，可以使用标题、列表、加粗等语法</p>
                                    </div>

                                    {/* 按钮组 */}
                                    <div className="flex justify-end gap-3 pt-2">
                                        <button
                                            type="button"
                                            onClick={() => setModalVisible(false)}
                                            className="px-5 py-2.5 border border-gray-200 rounded-xl text-gray-600 hover:bg-gray-50 hover:text-gray-800 focus:outline-none focus:ring-2 focus:ring-gray-200 text-sm font-medium transition-colors duration-200 flex items-center"
                                        >
                                            <svg className="w-4 h-4 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
                                            </svg>
                                            取消
                                        </button>
                                        <button
                                            type="submit"
                                            className="px-5 py-2.5 bg-gradient-to-r from-indigo-600 to-purple-600 text-white rounded-xl hover:from-indigo-700 hover:to-purple-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 text-sm font-medium transition-all duration-200 shadow-md hover:shadow-lg flex items-center"
                                        >
                                            <svg className="w-4 h-4 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 13l4 4L19 7" />
                                            </svg>
                                            创建主题
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* 一键生成确认弹窗 */}
            {generateConfirmVisible && (
                <div className="fixed inset-0 bg-black/70 flex items-center justify-center p-4 z-50 animate-fadein">
                    <div className="bg-white rounded-2xl w-full max-w-md shadow-2xl animate-scalein border border-gray-100 overflow-hidden">
                        {/* 左上角装饰 */}
                        <div className="absolute -top-10 -left-10 w-40 h-40 bg-gradient-to-br from-green-100 to-emerald-200 rounded-full opacity-70 blur-lg"></div>
                        {/* 右下角装饰 */}
                        <div className="absolute -bottom-10 -right-10 w-40 h-40 bg-gradient-to-tl from-emerald-100 to-green-200 rounded-full opacity-70 blur-lg"></div>

                        <div className="relative">
                            {/* 头部区域 - 带有渐变背景 */}
                            <div className="px-6 py-5 border-b border-gray-100 bg-gradient-to-r from-emerald-50 via-green-50 to-emerald-50">
                                <div className="flex items-center">
                                    <div className="bg-gradient-to-r from-green-500 to-emerald-600 text-white rounded-full p-2 mr-3 shadow-md">
                                        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
                                        </svg>
                                    </div>
                                    <h3 className="text-lg font-semibold text-gray-800 relative">
                                        <span className="relative z-10">确认一键生成</span>
                                        <span className="absolute inset-x-0 bottom-0 h-2 bg-green-100 -z-0 rounded-full transform -translate-y-2"></span>
                                    </h3>
                                </div>
                                <button
                                    onClick={() => setGenerateConfirmVisible(false)}
                                    className="absolute top-5 right-6 text-gray-400 hover:text-gray-600 transition-colors duration-200 hover:rotate-90 transform"
                                >
                                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
                                    </svg>
                                </button>
                            </div>

                            {/* 内容区域 */}
                            <div className="px-6 py-5 relative">
                                <div className="mb-5">
                                    {/* 提示图标和文本 */}
                                    <div className="flex items-start gap-4 mb-4 bg-gradient-to-r from-amber-50 to-yellow-50 p-4 rounded-xl border border-amber-200/70 shadow-inner">
                                        <div className="bg-amber-100 rounded-lg p-2 mt-0.5">
                                            <svg className="w-6 h-6 text-amber-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                                            </svg>
                                        </div>
                                        <div className="flex-1">
                                            <h4 className="text-amber-800 font-medium text-sm mb-1">确定要一键生成所有待执行主题的文章吗？</h4>
                                            <p className="text-amber-700/80 text-xs">
                                                此操作将批量处理所有待执行的主题，可能需要一些时间完成。
                                            </p>
                                        </div>
                                    </div>

                                    {/* 详细说明 */}
                                    <div className="space-y-3 mb-4 pl-2">
                                        <div className="flex items-start">
                                            <span className="inline-flex items-center justify-center w-5 h-5 rounded-full bg-green-100 text-green-700 text-xs font-bold mr-2">1</span>
                                            <p className="text-gray-600 text-sm">
                                                将为所有<span className="font-medium text-emerald-600">待执行</span>状态的主题生成文章
                                            </p>
                                        </div>
                                        <div className="flex items-start">
                                            <span className="inline-flex items-center justify-center w-5 h-5 rounded-full bg-green-100 text-green-700 text-xs font-bold mr-2">2</span>
                                            <p className="text-gray-600 text-sm">
                                                生成过程将在后台进行，您可以继续使用其他功能
                                            </p>
                                        </div>
                                        <div className="flex items-start">
                                            <span className="inline-flex items-center justify-center w-5 h-5 rounded-full bg-green-100 text-green-700 text-xs font-bold mr-2">3</span>
                                            <p className="text-gray-600 text-sm">
                                                文章生成完成后状态将自动更新为<span className="font-medium text-emerald-600">完成执行</span>
                                            </p>
                                        </div>
                                    </div>

                                    {/* 底部提示 */}
                                    <div className="text-xs text-gray-500 italic border-t border-gray-100 pt-2 pl-2">
                                        注：此操作无法撤销，请确认后继续
                                    </div>
                                </div>

                                {/* 按钮组 */}
                                <div className="flex justify-end gap-3 pt-2">
                                    <button
                                        type="button"
                                        onClick={() => setGenerateConfirmVisible(false)}
                                        className="px-5 py-2.5 border border-gray-200 rounded-xl text-gray-600 hover:bg-gray-50 hover:text-gray-800 focus:outline-none focus:ring-2 focus:ring-offset-1 focus:ring-gray-200 text-sm font-medium transition-all duration-200 flex items-center hover:shadow-sm"
                                    >
                                        <svg className="w-4 h-4 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
                                        </svg>
                                        取消
                                    </button>
                                    <button
                                        type="button"
                                        onClick={() => {
                                            setGenerateConfirmVisible(false);
                                            handleGenerateAll();
                                        }}
                                        className="px-5 py-2.5 bg-gradient-to-r from-green-500 to-emerald-600 text-white rounded-xl hover:from-green-600 hover:to-emerald-700 focus:outline-none focus:ring-2 focus:ring-offset-1 focus:ring-green-500 text-sm font-medium transition-all duration-200 shadow-md hover:shadow-lg flex items-center group"
                                    >
                                        <svg className="w-4 h-4 mr-1.5 group-hover:animate-pulse" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
                                        </svg>
                                        确认生成
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* 加载中覆盖层 */}
            {loading && topics.length > 0 && (
                <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50">
                    <div className="bg-white p-5 rounded-xl shadow-lg flex items-center gap-3 border border-gray-100">
                        <svg className="animate-spin h-5 w-5 text-indigo-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                        </svg>
                        <span className="text-gray-700 font-medium">加载中...</span>
                    </div>
                </div>
            )}

            {/* Toast提示 */}
            {toast.visible && (
                <div className="fixed bottom-6 right-6 z-50 animate-scalein">
                    <div className={`rounded-xl shadow-lg py-3 px-4 flex items-center gap-2 ${toast.type === 'success' ? 'bg-emerald-500 text-white' :
                        toast.type === 'error' ? 'bg-rose-500 text-white' :
                            'bg-indigo-500 text-white'
                        } border ${toast.type === 'success' ? 'border-emerald-400' :
                            toast.type === 'error' ? 'border-rose-400' :
                                'border-indigo-400'
                        }`}>
                        {toast.type === 'success' && (
                            <svg className="w-5 h-5 drop-shadow-sm" viewBox="0 0 20 20" fill="currentColor">
                                <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                            </svg>
                        )}
                        {toast.type === 'error' && (
                            <svg className="w-5 h-5 drop-shadow-sm" viewBox="0 0 20 20" fill="currentColor">
                                <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
                            </svg>
                        )}
                        {toast.type === 'info' && (
                            <svg className="w-5 h-5 drop-shadow-sm" viewBox="0 0 20 20" fill="currentColor">
                                <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2h-1V9z" clipRule="evenodd" />
                            </svg>
                        )}
                        <span className="font-medium drop-shadow-sm">{toast.message}</span>
                    </div>
                </div>
            )}

            {/* 添加自定义滚动条样式和背景效果 */}
            <style dangerouslySetInnerHTML={{
                __html: `
                body {
                    background-attachment: fixed;
                }
                
                .custom-scrollbar::-webkit-scrollbar {
                    width: 4px;
                }
                
                .custom-scrollbar::-webkit-scrollbar-track {
                    background: #f1f1f1;
                    border-radius: 10px;
                }
                
                .custom-scrollbar::-webkit-scrollbar-thumb {
                    background: #c7d2fe;
                    border-radius: 10px;
                }
                
                .custom-scrollbar::-webkit-scrollbar-thumb:hover {
                    background: #a5b4fc;
                }

                .markdown-content {
                    line-height: 1.6;
                }
                
                .markdown-content p {
                    margin-bottom: 0.75rem;
                }
                
                @keyframes scalein {
                    0% {
                        opacity: 0;
                        transform: scale(0.95);
                    }
                    100% {
                        opacity: 1;
                        transform: scale(1);
                    }
                }
                
                @keyframes fadein {
                    0% {
                        opacity: 0;
                    }
                    100% {
                        opacity: 1;
                    }
                }
                
                @keyframes gentle-pulse {
                    0% {
                        opacity: 0.9;
                    }
                    50% {
                        opacity: 1;
                    }
                    100% {
                        opacity: 0.9;
                    }
                }
                
                @keyframes floating {
                    0% {
                        transform: translateY(0px);
                    }
                    50% {
                        transform: translateY(-5px);
                    }
                    100% {
                        transform: translateY(0px);
                    }
                }
                
                .animate-gentle-pulse {
                    animation: gentle-pulse 3s ease-in-out infinite;
                }
                
                .animate-floating {
                    animation: floating 4s ease-in-out infinite;
                }
                
                .animate-scalein {
                    animation: scalein 0.2s ease-out;
                }
                
                .animate-fadein {
                    animation: fadein 0.2s ease-out;
                }
            `}} />
        </div>
    );
};

export default TopicSquare; 